<template>
  <div>
    <el-form ref="form" label-width="100px">
      <el-form-item label="SPU名称">
        <el-input v-model='spuForm.spuName' placeholder="SPU名称"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select v-model="spuForm.tmId" placeholder="请选择品牌">
          <el-option :label="tm.tmName" :value="tm.id" v-for="(tm,index) in trademarkList" :key="tm.id"></el-option>
        </el-select>
      </el-form-item>
      <!--      textarea区域-->
      <el-form-item label="SPU描述" prop="description">
        <el-input rows="4" type="textarea" v-model='spuForm.description' placeholder="SPU描述"></el-input>
      </el-form-item>
      <!--      照片墙 upload
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"-->
      <el-form-item label="SPU照片">
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :file-list="spuImageList"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <!--      :visible.sync="dialogVisible"  :src="dialogImageUrl"-->
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select
          v-model='saleAttrIdName'
          :placeholder="computedAttrList.length?`还有${computedAttrList.length}个未选择`:'没有啦'">
          <el-option :label="ct.name" :value="`${ct.id}:${ct.name}`" v-for="(ct,index) in computedAttrList"
                     :key="ct.id"></el-option>
        </el-select>
        <el-button type="primary" icon="el-icon-plus" :disabled="!saleAttrIdName" @click="addSaleAttr">添加销售属性
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-table
          :data="spuForm.spuSaleAttrList"
          style="width: 100%" border>
          <el-table-column
            prop="prop"
            align="center"
            type="index"
            label="序号"
            width="80">
          </el-table-column>
          <el-table-column
            prop="saleAttrName"
            label="属性名"
            width="width">
          </el-table-column>
          <el-table-column
            prop="prop"
            label="属性值名称列表"
            width="width">
            <template slot-scope="{row,$index}">
              <el-tag
                v-for="(spuSaleAttrValue,index) in row.spuSaleAttrValueList"
                :key="spuSaleAttrValue.id"
              >{{ spuSaleAttrValue.saleAttrValueName }}
              </el-tag>

              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model="row.saleAttrValueName"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="toButton(row)"
                @blur="toButton(row)"
              ></el-input>
              <el-button v-else class="button-new-tag" size="small" @click="toInput(row)">+添加</el-button>
            </template>

          </el-table-column>
          <el-table-column
            prop="prop"
            label="操作"
            width="width">
            <template slot-scope="{row,$index}">
              <HintButton
                type="danger"
                size="mini"
                icon="el-icon-delete"
                title="删除销售属性值"
                @click="spuForm.spuSaleAttrList.splice($index,1)"
              ></HintButton>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
export default {
  data() {
    return {
      spuForm: {
        category3Id: 0,
        spuName: "",
        description: "",
        tmId: "",
        spuImageList: [
          // {
          //   id: 0,
          //   imgName: "string",
          //   imgUrl: "string",
          //   spuId: 0,
          // },
        ],
        spuSaleAttrList: [
          // {
          // baseSaleAttrId: 0,
          // id: 0,
          // saleAttrName: "string",
          // spuId: 0,
          // spuSaleAttrValueList: [
          // {
          //   baseSaleAttrId: 0,
          //   id: 0,
          //   isChecked: "string",
          //   saleAttrName: "string",
          //   saleAttrValueName: "string",
          //   spuId: 0,
          // },
          // ],
          // },
        ], //spu自己的销售属性列表
      },
      spuImageList: [],
      trademarkList: [],
      baseSaleAttrList: [],
      dialogVisible: false,//照片墙中的参数 不一定有用
      dialogImageUrl: "",//照片墙中的参数 不一定有用
      saleAttrIdName: ''
    }
  },
  methods: {
    //删除照片时
    handleRemove(file, fileList) {
      /*    console.log(file, fileList);*/
      this.spuImageList = fileList
    },
    //扩大图
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //上传成功
    handleSuccess(res, file, fileList) {
      this.spuImageList = fileList
    },
    //初始化函数 此函数是点击父组件中的修改SPU按钮触发的4个请求 在写好的页面中找4个
    async getInitUpdateSpuFormData(row) {
      //根据spu的id获取详情
      //http://localhost:9529/dev-api/admin/product/getSpuById/1858
      const result1 = await this.$API.spu.get(row.id)
      if (result1.code === 200 || result1.code === 20000) {
        this.spuForm = result1.data
      }
      //根据id获取图片信息
      //http://localhost:9529/dev-api/admin/product/spuImageList/1858
      const result2 = await this.$API.sku.getSpuImageList(row.id)
      if (result2.code === 200 || result2.code === 20000) {
        //如果新上传了图片，那么新上传的图片和老的图片内部属性是不一样的 需要添加一下imgName imgUrl
        let spuImageList = result2.data
        spuImageList.forEach(item => {
          item.name = item.imgName
          item.url = item.imgUrl
        })
        this.spuImageList = spuImageList
      }
      //获取品牌列表
      //http://localhost:9529/dev-api/admin/product/baseTrademark/getTrademarkList
      const result3 = await this.$API.trademark.getList()
      if (result3.code === 200 || result3.code === 20000) {
        this.trademarkList = result3.data
      }
      //获取所有属性列表
      //http://localhost:9529/dev-api/admin/product/baseSaleAttrList
      const result4 = await this.$API.spu.getSaleAttrList()
      if (result4.code === 200 || result4.code === 20000) {
        this.baseSaleAttrList = result4.data
      }
    },
    //初始化函数 此函数是点击父组件中的添加SPU按钮触发的2个请求
    async getInitAddSpuFormData() {
      //获取品牌列表
      //http://localhost:9529/dev-api/admin/product/baseTrademark/getTrademarkList
      const result3 = await this.$API.trademark.getList()
      if (result3.code === 200 || result3.code === 20000) {
        this.trademarkList = result3.data
      }
      //获取所有属性列表
      //http://localhost:9529/dev-api/admin/product/baseSaleAttrList
      const result4 = await this.$API.spu.getSaleAttrList()
      if (result4.code === 200 || result4.code === 20000) {
        this.baseSaleAttrList = result4.data
      }
    },
    //添加销售属性
    addSaleAttr() {
      //结构    spuSaleAttrList
      /*  {
          saleAttrValueName: "string",
            baseSaleAttrId ：1   就是当前属性的id
        },*/
      let [baseSaleAttrId, saleAttrName] = this.saleAttrIdName.split(":")
      let obj = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: []
      }
      this.spuForm.spuSaleAttrList.push(obj)
      this.saleAttrName = ''
    },
    //点击button按钮切换到input
    toInput(row) {
      //后加的属性
      this.$set(row, 'inputVisible', true)//添加响应式inputVisible 为true
      this.$set(row, 'saleAttrValueName', "")//添加响应式saleAttrValueName
      //自动获取焦点
      this.$nextTick(() => {
        this.$refs.saveTagInput.focus()
      })
    },
    //输入值后或者失去焦点后切换成button
    toButton(row) {
      let {baseSaleAttrId, saleAttrValueName} = row
      let obj = {baseSaleAttrId, saleAttrValueName}
      //判断输入的值 是否是空值
      if (saleAttrValueName.trim() === '') {
        row.saleAttrValueName = ''// 清空输入框
        row.inputVisible = false// 切换到button
        return //结束本函数
      }
      //  判断是否重复
      let isRepeat = row.spuSaleAttrValueList.some(item => {
        return item.saleAttrValueName === saleAttrValueName
      })
      if (isRepeat) {
        this.$message.success('属性值不能重复')
        row.saleAttrValueName = ""//清空输入框
        return;
      }
      //添加到数组中
      row.spuSaleAttrValueList.push(obj)
      //切换成button
      row.inputVisible = false
      //清空输入框
      row.saleAttrValueName = ""
    },
    //保存
    async save() {
      //请求参数
      let {spuForm, spuImageList, category3Id} = this
      //整理参数
      spuForm.category3Id = category3Id
      spuForm.spuSaleAttrList.forEach(item => {
        delete item.inputVisible
        delete item.saleAttrValueName
      })
      spuForm.spuImageList=spuImageList.map(item => {
        return {
          imgName: item.name,
          imgUrl: item.imgUrl || item.response.data
        }
      })
      //发请求
      try {
        const result = await this.$API.spu.addUpdate(spuForm)
        if (result.code === 200 || result.code === 20000) {
          //成功
          this.$message.success('保存属性成功')
          this.$emit('update:visible', false) //返回父组件 列表页
          this.$emit('backSuccess')//通知父组件回来了 清空标志位
          this.resetData()//清空data中的数据
        } else {
          this.$message.error('保存属性失败')
        }
      } catch (error) {
        //失败
        this.$message.error('保存属性请求失败')
      }
    },
    //清空data中的数据
    resetData() {
      this.spuForm = {
        category3Id: 0,
        spuName: "",
        description: "",
        tmId: "",
        spuImageList: [
          // {
          //   id: 0,
          //   imgName: "string",
          //   imgUrl: "string",
          //   spuId: 0,
          // },
        ],
        spuSaleAttrList: [
          // {
          // baseSaleAttrId: 0,
          // id: 0,
          // saleAttrName: "string",
          // spuId: 0,
          // spuSaleAttrValueList: [
          // {
          //   baseSaleAttrId: 0,
          //   id: 0,
          //   isChecked: "string",
          //   saleAttrName: "string",
          //   saleAttrValueName: "string",
          //   spuId: 0,
          // },
          // ],
          // },
        ], //spu自己的销售属性列表
      },
        this.spuImageList = [],
        this.trademarkList = [],
        this.baseSaleAttrList = [],
        this.dialogVisible = false,//照片墙中的参数 不一定有用
        this.dialogImageUrl = "",//照片墙中的参数 不一定有用
        this.saleAttrIdName = ''
    },
    //点击取消按钮 清空输入框切换到父组件列表页 通知父组件回来了 清空标志位
    cancel(){
      this.$emit('update:visible',false)
      this.resetData()
      this.$emit('cancelBack')
    }
  },
  computed: {
    //计算属性 baseSaleAttrList
    computedAttrList() {
      // 从总的列表当中过滤，和小的列表当中名字都不一样的项
      return this.baseSaleAttrList.filter(item => {
        return this.spuForm.spuSaleAttrList.every(item1 => {
          return item.name !== item1.saleAttrName
        })
      })
    }
  }
}
</script>
